package com.sumer.psychology.microblog.infrastructure.persistence.hibernate;


import com.sumer.psychology.common.persistence.hibernate.AbstractHibernateRepository;
import com.sumer.psychology.microblog.domain.model.MicroBlog;
import com.sumer.psychology.microblog.domain.model.MicroBlogAvailability;
import com.sumer.psychology.microblog.domain.model.MicroBlogId;
import com.sumer.psychology.microblog.domain.model.MicroBlogRepository;
import org.hibernate.Query;

import java.util.UUID;

/**
 * User: zhenguang.zhu
 * Date: 2014/9/2
 * Time: 14:33
 */
public class HibernateMicroBlogRepository extends AbstractHibernateRepository implements MicroBlogRepository {
    @Override
    public MicroBlogId nextIdentity() {
        return new MicroBlogId(UUID.randomUUID().toString());
    }

    @Override
    public void add(MicroBlog aMicroBlog) {
        session().saveOrUpdate(aMicroBlog);
    }

    @Override
    public MicroBlog ofMicroBlogId(MicroBlogId microBlogId) {
        Query query = session()
                .createQuery("from MicroBlog where microBlogId=:microBlogId and availability=:availability")
                .setParameter("microBlogId", microBlogId)
                .setParameter("availability", MicroBlogAvailability.ACTIVE);

        return (MicroBlog) query.uniqueResult();
    }
}
